package com.hljcert.data.service.common.config;

import cn.dev33.satoken.exception.NotLoginException;
import com.hljcert.data.service.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public Result<Void> businessException(BusinessException ex) {
        log.error("businessException", ex);
        return Result.error(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler(NotLoginException.class)
    public Result<Void> notLoginException(NotLoginException ex) {
        log.warn("没有登录", ex);
        return Result.noauth("未登录");
    }

    /**
     * 参数校验异常 对应 @Valid 注解
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> methodArgumentNotValidException(MethodArgumentNotValidException ex) {
        // 每次只响应第一次错误提示
        FieldError fieldError = ex.getBindingResult().getFieldError();
        if (fieldError == null) {
            return Result.error(StatusEnum.AUTH_ERR.getCode(), StatusEnum.AUTH_ERR.getMsg());
        }
        return Result.error(StatusEnum.PARAM_ERR.getCode(), fieldError.getDefaultMessage());
    }

    @ExceptionHandler(BindException.class)
    public Result<Void> bindArgumentNotValidException(BindException ex) {
        // 每次只响应第一次错误提示
        FieldError fieldError = ex.getBindingResult().getFieldError();
        if (fieldError == null) {
            return Result.error(StatusEnum.AUTH_ERR.getCode(), StatusEnum.AUTH_ERR.getMsg());
        }
        return Result.error(StatusEnum.PARAM_ERR.getCode(), fieldError.getDefaultMessage());
    }


    /**
     * 全局兜底异常  触发次异常代表着需要我们关注
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result<Void> exception(Exception ex) {
        log.error("未知错误", ex);
        return Result.error("未知错误");
    }
}
